<template>
  <page-header-wrapper>
    <a-card :bordered="false" class="card_top_padding no_need_padding" style="margin-bottom: 11px" v-if="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="20">
            <a-col :md="8" :sm="24">
              <a-form-item label="角色ID">
                <a-input placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select placeholder="请选择" default-value="-1">
                  <a-select-option value="-1">全部</a-select-option>
                  <a-select-option value="1">启用</a-select-option>
                  <a-select-option value="0">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary">查询</a-button>
                <a-button style="margin-left: 8px">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="card_style_re">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <span></span>
        <a-button type="primary" @click="onAdd" icon="plus">新建</a-button>
      </div>
      <s-table row-key="id" size="default" :columns="columns" :data="loadData" ref="table">
        <a-tag :color="text == 1 ? 'blue' : 'red'" slot="status" slot-scope="text">{{ text | statusFilter }}</a-tag>
        <span slot="describe" slot-scope="text">{{ text }}</span>
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除该角色吗？" @confirm="handleDelete(record)">
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </s-table>

      <a-modal
        :title="isNew ? '创建角色' : '编辑角色'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="visible"
        @ok="handleOk"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色名称" hasFeedback>
            <a-input
              placeholder="起一个名字"
              v-decorator="['name', { rules: [{ required: true, message: '请填写角色名称' }] }]"
            />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
            <a-select label-in-value v-decorator="['status', { initialValue: statusSelectValue }]">
              <a-select-option :value="1">启用</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注" hasFeedback>
            <a-textarea :rows="2" id="describe" v-decorator="['describe']" />
          </a-form-item>

          <a-divider>拥有权限</a-divider>
          <a-tree
            :treeData="permissionTree"
            :checkable="true"
            :selectable="false"
            :defaultCheckedKeys="defaultCheckedKeys"
            @check="onTreeCheck"
          ></a-tree>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import pick from 'lodash.pick'
import { STable } from '@/components'
import {
  getRoleList,
  getPermission,
  createRole,
  editRole,
  deleteRole,
  saaSgetRoleList,
  saaSgetPermission,
  saaScreateRole,
  saaSeditRole,
  saaSdeleteRole,
} from '@/api/auth'

const STATUS = {
  1: '启用',
  0: '禁用',
}

const columns = [
  {
    title: '角色名称',
    dataIndex: 'name',
  },
  {
    title: '备注',
    dataIndex: 'describe',
    scopedSlots: { customRender: 'describe' },
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    width: '150px',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'RoleList',
  components: {
    STable,
  },
  data() {
    return {
      description: '后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',
      isNew: false,
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      form: this.$form.createForm(this),
      // 表头
      columns,
      // 权限树
      permissionTree: [],
      currentId: 0,
      // 已选择的权限
      selectedPermission: [],
      modalLoading: false,
      defaultCheckedKeys: [],
      statusSelectValue: { key: '1', label: '启用' },
      type: 1,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        if (this.type === 0) {
          return saaSgetRoleList(parameter).then((res) => {
            return res.data
          })
        }

        return getRoleList(parameter).then((res) => {
          return res.data
        })
      },
    }
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
  },
  created() {
    let { type } = this.$route.meta
    this.type = type

    if (type === 0) {
      saaSgetPermission({}).then((res) => {
        this.permissionTree = res.data
      })
      return
    }

    getPermission({}).then((res) => {
      this.permissionTree = res.data
    })
  },
  methods: {
    handleEdit(record) {
      this.isNew = false
      this.visible = true
      this.currentId = record.id
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['key', 'describe', 'name']))
        this.form.setFieldsValue({ status: { key: record.status, label: record.status === '1' ? '启用' : '禁用' } })
      })
      this.defaultCheckedKeys = []
      if (record.data) {
        this.defaultCheckedKeys = record.data
      }
    },
    submitCallBack(res, msg = '角色编辑成功！') {
      this.modalLoading = false
      if (res.code !== 0) {
        this.$error({
          content: res.msg,
        })
      } else {
        this.$message.success(msg)
        this.visible = false
        this.$refs.table.refresh()
      }
    },
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }
        values.data = this.selectedPermission
        if (this.selectedPermission.length === 0) {
          values.data = this.defaultCheckedKeys
        }
        values.status = values.status.key
        this.modalLoading = true
        if (this.isNew) {
          if (this.type === 0) {
            saaScreateRole(values).then((res) => {
              this.submitCallBack(res, '角色创建成功！')
            })
            return
          }

          createRole(values).then((res) => {
            this.submitCallBack(res, '角色创建成功！')
          })
        } else {
          if (this.type === 0) {
            saaSeditRole({ id: this.currentId, ...values }).then((res) => {
              this.submitCallBack(res, '角色创建成功！')
            })
            return
          }

          editRole({ id: this.currentId, ...values }).then((res) => {
            this.submitCallBack(res)
          })
        }
      })
    },
    onAdd: function () {
      this.isNew = true
      this.currentId = 0
      this.visible = true
      this.defaultCheckedKeys = []
    },
    onTreeCheck: function (checkedKeys, info) {
      console.log('checkedKeys', checkedKeys)
      this.selectedPermission = checkedKeys
    },
    handleDelete: function (record) {
      const hide = this.$message.loading('删除中...', 0)

      if (this.type === 0) {
        saaSdeleteRole({
          id: record.id,
        }).then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('角色删除成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        return
      }

      deleteRole({
        id: record.id,
      }).then((res) => {
        hide()
        if (res.code === 0) {
          this.$message.success('角色删除成功！')
          this.$refs.table.refresh()
        } else {
          this.$error({
            content: res.msg,
          })
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
</style>
